import { useState, useEffect } from 'react';
import { ImageBackground, FlatList, StyleSheet, ToastAndroid, TouchableOpacity, Text, View, Image } from 'react-native';
import { Entypo } from '@expo/vector-icons';
import { useAuth } from '../context/AuthProvider';

const Pay = ({ navigation, route }) => {
    const { user } = useAuth()
    const [page, setPage] = useState(1);
    const [list, setList] = useState([]);
    const [list1, setList1] = useState([]);
    const [refreshing, setRefreshing] = useState(false);
    const shopId = route.params.id
    const shopState = route.params.state
    const addressId = route.params.addressId;
    const shopName = route.params.shopName

    useEffect(() => {
        navigation.setOptions({
            title: '支付',
        })
        fetch('http://10.7.89.174:3000/addressList', {
            method: 'POST',
            body: JSON.stringify({
                addressId: addressId,
            })
        })
            .then(res => res.json())
            .then(res => {
                setRefreshing(false)
                if (page == 1) {
                    console.log(res.List);
                    setList1(res.List)
                } else {
                    setList1([...list1, ...res.data.content])
                }
            })
        fetch('http://10.7.89.174:3000/payList', {
            method: 'POST',
            body: JSON.stringify({
                shopId: shopId,
            })
        })
            .then(res => res.json())
            .then(res => {
                setRefreshing(false)
                setList(res.List)
            })
    }, [page,list1])
    // 取消支付按钮
    const noPay = () => {
        fetch('http://10.7.89.174:3000/cancelPay', {
            method: 'POST',
            body: JSON.stringify({
                shopId: shopId,
                shopState: shopState
            })
        })
        .then(res => res.json())
        .then(res => {
            if (res.code == 200) {
                ToastAndroid.show("取消支付", ToastAndroid.SHORT);
                navigation.navigate('Shop')
            } else {
                ToastAndroid.show("取消失败", ToastAndroid.SHORT);
            }
        })
    };
    // 支付按钮
    const onPay = () => {
        fetch('http://10.7.89.174:3000/onPay', {
            method: 'POST',
            body: JSON.stringify({
                shopId: shopId,
                shopState: shopState,
            })
        })
        .then(res => res.json())
        .then(res => {
            // console.log(8888);
            // console.log(shopName);
            // console.log(user.userName);
            if (res.code == 200) {
                navigation.navigate('Shop')
                ToastAndroid.show("支付成功", ToastAndroid.SHORT);
            } else {
                ToastAndroid.show("支付失败", ToastAndroid.SHORT);
            }
        })

        
        fetch('http://10.7.89.174:3000/changeMoney', {
            method: 'POST',
            body: JSON.stringify({
                shopId: shopId,
                shopName:shopName,
                userName:user.userName
            })
        })
        .then(res => res.json())
        .then(res => {
            if (res.code == 200) {
                navigation.navigate('Shop')
                ToastAndroid.show("支付成功", ToastAndroid.SHORT);
            }
            if(res.code==401){
                ToastAndroid.show("您的余额为0,请先去充值", ToastAndroid.SHORT);
                navigation.navigate('Mypackage')                
            } 
            else {
                ToastAndroid.show("支付失败", ToastAndroid.SHORT);
            }
        })
    };
    const onRefresh = () => {
        setRefreshing(true);
        setPage(1);
    }
    const onEnd = () => {
        setPage(page + 1)
    }
    const ToAddressChoose = () => {
        navigation.navigate('ChooseAddress', { id: shopId, state: shopState })
    }
    const renderItem1 = ({ item }) => (
        <View >
            <View style={styles.address}>
                <View>
                    <Text style={styles.addresstext}>收货人：{item.addressName}</Text>
                </View>
                <View>
                    <Text style={{ fontSize: 18 }}>具体地址：{item.park}{item.building}号楼</Text>
                    <Entypo
                        style={styles.choose}
                        name='chevron-right'
                        size={36}
                        onPress={ToAddressChoose}
                    />
                </View>
                <Text style={styles.addresstext}>联系方式：{item.phoneNum}</Text>
            </View>
        </View>
    )
    const renderItem = ({ item }) => (
        <View >
            <View style={{ marginLeft: '3%' }}>
                {/* 出租人头像、用户名等信息 */}
                <View style={{ flexDirection: 'row' }}>
                    <View>
                        <Image
                            style={{ width: 50, height: 50 ,borderRadius:50}}
                            source={{
                                uri:'data:image/jpeg/jpg;base64,'+ item.avatarUrl
                            }}
                        />
                    </View>
                    <View style={styles.typeView}>
                        <Text style={styles.type}>{item.userName}</Text>
                    </View>
                </View>
                <View style={styles.item}>
                    <View style={styles.itemImg}>
                        <Image
                            style={{ width: 80, height: 80, }}
                            source={{
                                uri: 'data:image/jpeg/jpg;base64,'+item.shopImage
                            }}
                        />
                    </View>
                    <View style={styles.itemText}>
                        <Text style={{ marginTop: 10, }}>{item.shopText}</Text>
                    <Text style={{ marginTop: 10, }}>押金￥{item.shopDeposit}</Text>
                        <Text style={styles.pricetext}>单价￥{item.shopPrice}</Text>
                    </View>
                </View>
                <View>
                    <Text style={styles.addprice}>
                        ￥{item.shopPrice}
                    </Text>
                    <TouchableOpacity style={[styles.CancelBtn]} >
                        <Text style={styles.uploadText} onPress={() => noPay()}>取消支付</Text>
                    </TouchableOpacity>
                    <TouchableOpacity style={[styles.PayBtn]} >
                        <Text style={styles.uploadText} onPress={() => onPay()}>支  付</Text>
                    </TouchableOpacity>
                </View>
            </View>
        </View>
    )
    return (
        <View style={styles.container}>
            <ImageBackground source={require('../img/bgimg.jpg')} style={styles.bgimg}>
                <FlatList
                    ListEmptyComponent={
                        <View style={styles.chooseBox}>
                            <Text style={styles.addressText} onPress={() => ToAddressChoose()}><Entypo name="address" size={26} color="black" />点击选择收货地址</Text>
                        </View>
                    }
                    onRefresh={onRefresh}
                    refreshing={refreshing}
                    data={list1}
                    renderItem={renderItem1}
                    onEndReached={onEnd}
                    keyExtractor={item => item.id}
                />
                <FlatList
                style={{marginTop:"-40%"}}
                    ListEmptyComponent={<Text>暂无数据</Text>}
                    onRefresh={onRefresh}
                    refreshing={refreshing}
                    data={list}
                    renderItem={renderItem}
                    onEndReached={onEnd}
                    keyExtractor={item => item.id}
                />
            </ImageBackground>
        </View>
    );
}

const styles = StyleSheet.create({
    container: {
        flex: 1
    },
    bgimg: {
        flex: 1,
        resizeMode: "cover",
        justifyContent: "center",
    },
    address: {
        marginBottom: 15,
        marginTop: '10%',
        marginLeft: '3%'
    },
    addresstext: {
        fontSize: 18,
        marginTop: 8,
        marginBottom: 8,
    },
    choose: {
        marginLeft: 'auto',
        marginTop: -35,
    },
    typeView: {
        marginRight: 20,
        paddingHorizontal: 5,
        borderRadius: 3
    },
    addprice: {
        marginTop: 25,
        fontSize: 20,
        color: 'red',
    },
    CancelBtn: {
        marginLeft: 'auto',
        marginRight: 100,
        marginTop: -30,
        height: 35,
        width: 80,
        backgroundColor: 'white',
        justifyContent: 'center',
    },
    PayBtn: {
        marginLeft: 'auto',
        marginRight: 10,
        marginTop: -35,
        height: 35,
        width: 80,
        backgroundColor: 'white',
        justifyContent: 'center',
    },
    uploadText: {
        textAlign: 'center',
        color: 'white',
        textAlignVertical: 'center',
        borderWidth: 1,
        borderColor: '#cacaca',
        fontSize: 15,
        height: 30,
        borderRadius: 15,
        backgroundColor: 'red'
    },
    item: {
        marginTop: 5,
        backgroundColor: "white",
        height: 100,
    },
    itemImg: {
        borderWidth: 1,
        width: 80,
        height: 80,
        marginLeft: 15,
        marginTop: 10,
    },
    itemText: {
        width: 280,
        height: 80,
        marginLeft: 125,
        marginTop: -80,
    },
    pricetext: {
        marginLeft: 'auto',
        marginTop: -30,
        fontSize: 17,
        color: 'red',
    },
    chooseBox:{
        marginTop:"22%",
    },
    addressText: {
        textAlign: 'center',
        textAlignVertical: 'center',
        fontSize:20
    },
});

export default Pay; 